package thread.notifydemo;

public class Demo2 {
   //Declare an object
  public Object object=new Object();
    //Declare a variable to store the number of objects
    int num=0;

    //Create a method to add an object
    public void add(){
        //Synchronize the object
        synchronized (object){
            //Check if the number of objects is not 0
            while (num!=0){
                try {
                    //Wait until the object is notified
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //Increment the number of objects
            num++;
            //Print the name of the thread and the number of objects
            System.out.println(Thread.currentThread().getName()+"\r"+num);
            //Notify the object
            object.notify();
        }

    }
    public void dre(){
        synchronized (object){
            while (num==0){
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"\r"+num);
            object.notify();
        }
    }

    public static void main(String[] args) {

        Demo2 demo2=new Demo2();

        for (int i=0;i<2;i++){
            new Thread(()->{
                demo2.add();
            },"aa").start();
        }
        for (int i=0;i<2;i++){
            new Thread(()->{
                demo2.dre();
            },"bb").start();
        }

    }
}